<template>
  <div>
    <el-upload
      class="upload-demo"
      action
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :limit="1"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      :auto-upload="false"
    >
      <Button type="primary">导入XLSX文件</Button>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileTemp: ""
    };
  },
  methods: {
    //上传文件
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      console.log(file);
      if (this.fileTemp) {
        // if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type == 'application/vnd.ms-excel')){
        this.importfxx(this.fileTemp);
        // }
        // else {
        // this.$Message.error('附件格式错误，请删除后重新上传！')
        // }
      } else {
        this.$Message.error("请上传附件！");
      }
    },
    //超出最大上传文件数量
    handleExceed() {
      this.$Message.error("超出最大上传文件数量的限制");
      return false;
    },
    //移除文件
    handleRemove(file, fileList) {
      this.fileTemp = null;
      this.$emit("xlsxData", []);
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          _this.$emit("xlsxData", outdata);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    }
  }
};
</script>

<style scoped>
</style>
